package main

import (
    "fmt"
    "net"
    "time"
)

func startMaster() {
    listener, err := net.Listen("tcp", config.MasterAddr)
    if err != nil {
        fmt.Println("Error starting master:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Master started on", config.MasterAddr)

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting connection:", err)
            continue
        }
        go handleMasterConnection(conn)
    }
}

func handleMasterConnection(conn net.Conn) {
    defer conn.Close()

    for {
        message, err := receiveIEC104Message(conn)
        if err != nil {
            fmt.Println("Error receiving message:", err)
            return
        }

        if !verifyAuthKey(message.Data, config.AuthKey, message.AuthKey) {
            fmt.Println("Authentication failed")
            return
        }

        timestamp := time.Now().Format(time.RFC3339)
        switch message.Type {
        case "C":
            fmt.Printf("[%s] Data call: %s\n", timestamp, message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "R", Data: "01", AuthKey: generateAuthKey("01", config.AuthKey)})
        case "R":
            fmt.Printf("[%s] Remote control: %s\n", timestamp, message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "A", Data: "02", AuthKey: generateAuthKey("02", config.AuthKey)})
        case "A":
            fmt.Printf("[%s] Remote adjustment: %s\n", timestamp, message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "S", Data: "03", AuthKey: generateAuthKey("03", config.AuthKey)})
        case "S":
            fmt.Printf("[%s] Remote signal: %s\n", timestamp, message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "M", Data: "04", AuthKey: generateAuthKey("04", config.AuthKey)})
        case "M":
            fmt.Printf("[%s] Remote measurement: %s\n", timestamp, message.Data)
            sendIEC104Message(conn, IEC104Message{Type: "F", Data: "05", AuthKey: generateAuthKey("05", config.AuthKey)})
        case "X":
            handleSingleCommand(conn, message.Data)
        case "Y":
            handleDoubleCommand(conn, message.Data)
        case "Z":
            handleStepRegulationCommand(conn, message.Data)
        case "P":
            handleSetPointCommand(conn, message.Data)
        case "FILE": // 处理文件传输请求
            fmt.Printf("[%s] File transfer request received: %s\n", timestamp, message.Data)
            sendFileData(conn, message.Data)
        default:
            fmt.Printf("[%s] Unknown message type: %s\n", timestamp, message.Type)
        }
    }
}

// 新增函数：发送文件数据
func sendFileData(conn net.Conn, fileName string) {
    timestamp := time.Now().Format(time.RFC3339)
    message := fmt.Sprintf("File data for %s at %s", fileName, timestamp)
    sendIEC104Message(conn, IEC104Message{Type: "DATA", Data: message, AuthKey: generateAuthKey(message, config.AuthKey)})
    fmt.Println("File data sent:", message)
}

// 新增函数：处理设点命令
func handleSetPointCommand(conn net.Conn, command string) {
    fmt.Printf("Handling set point command: %s\n", command)
    // 这里可以添加实际的设点命令处理逻辑
    sendIEC104Message(conn, IEC104Message{Type: "P", Data: "09", AuthKey: generateAuthKey("09", config.AuthKey)})
}

// 新增函数：处理单命令
func handleSingleCommand(conn net.Conn, command string) {
    fmt.Printf("Handling single command: %s\n", command)
    // 这里可以添加实际的单命令处理逻辑
    sendIEC104Message(conn, IEC104Message{Type: "X", Data: "06", AuthKey: generateAuthKey("06", config.AuthKey)})
}

// 新增函数：处理双命令
func handleDoubleCommand(conn net.Conn, command string) {
    fmt.Printf("Handling double command: %s\n", command)
    // 这里可以添加实际的双命令处理逻辑
    sendIEC104Message(conn, IEC104Message{Type: "Y", Data: "07", AuthKey: generateAuthKey("07", config.AuthKey)})
}

// 新增函数：处理步调节命令
func handleStepRegulationCommand(conn net.Conn, command string) {
    fmt.Printf("Handling step regulation command: %s\n", command)
    // 这里可以添加实际的步调节命令处理逻辑
    sendIEC104Message(conn, IEC104Message{Type: "Z", Data: "08", AuthKey: generateAuthKey("08", config.AuthKey)})
}

// 新增函数：执行遥控命令
func executeRemoteControl(command string) {
    fmt.Printf("Executing remote control command: %s\n", command)
    // 这里可以添加实际的遥控命令执行逻辑
    // 例如：控制设备开关、调整参数等
}